package com.bsoft.gol.hcs.satisfaction.service.impl;

import com.bsoft.gol.hcs.base.BaseHisPlateformXmlRequest;
import com.bsoft.gol.hcs.base.BaseHisPlateformXmlResponse;
import com.bsoft.gol.hcs.base.MsgHeaderRequest;
import com.bsoft.gol.hcs.clinical.bean.req.QueryCheckItemListReq;
import com.bsoft.gol.hcs.clinical.bean.req.QueryInspectionItemListReq;
import com.bsoft.gol.hcs.clinical.bean.response.QueryCheckItemListResp;
import com.bsoft.gol.hcs.clinical.bean.response.QueryCheckItemResponse;
import com.bsoft.gol.hcs.clinical.bean.response.QueryInspectionItemListResp;
import com.bsoft.gol.hcs.clinical.bean.vo.TreatmentCodeVo;
import com.bsoft.gol.hcs.clinical.service.IExamineService;
import com.bsoft.gol.hcs.clinical.service.IMedicalSkillsService;
import com.bsoft.gol.hcs.clinical.service.impl.ElectronicMedicalService;
import com.bsoft.gol.hcs.clinical.service.impl.StandardDrugService;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.common.service.impl.BaseDataServiceImpl;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.xml.jaxb.JAXBUtils;
import com.bsoft.gol.hcs.enumcase.InspectionEmum;
import com.bsoft.gol.hcs.enumcase.SurgicalLevelEnum;
import hcn.util.BaseResponse;
import hcn.service.commonClinical.qo.ParamsOrgQo;
import com.bsoft.gol.hcs.his.service.impl.DictionaryHisServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.bsoft.gol.hcs.satisfaction.bean.qo.DictionaryQo;
import com.bsoft.gol.hcs.satisfaction.bean.vo.DictionaryVo;
import com.bsoft.gol.hcs.satisfaction.dao.SurgicalTypeDAO;
import com.bsoft.gol.hcs.satisfaction.service.ISatisfactionSurverRuleService;
import com.bsoft.gol.hcs.specialist.dao.TreatmentRecordDAO;
import com.bsoft.gol.hcs.task.bean.request.QueryDrugstoreListRequest;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import org.atag.util.common.RpcUtil;
import com.bsoft.gol.hcs.utils.WhisClientUtil;
import com.bsoft.gol.hcs.visitrecord.bean.vo.QueryDrugstoreListVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SsdevService("satisfactionSurveyRule")
public class SatisfactionSurveyRuleService implements ISatisfactionSurverRuleService {
    private final static Logger logger = LoggerFactory.getLogger(SatisfactionSurveyRuleService.class);


    @Autowired
    private BaseDataServiceImpl baseDataService;
    @Autowired
    private ElectronicMedicalService electronicMedicalService;
    @Autowired
    private StandardDrugService standardDrugService;
    @Autowired
    private DictionaryHisServiceImpl dictionaryHisService;
    @Autowired
    private SurgicalTypeDAO surgicalTypeDAO;
    @Autowired
    private IMedicalSkillsService medicalSkillsService;
    @Autowired
    private IExamineService examineService;
    @Autowired
    private TreatmentRecordDAO treatmentRecordDAO;
    @Value("${project_source}")
    private String projectSource;
    @Value("${phis_path_url}")
    public String PHIS_PATH_URL;

    @Override
    public List<DictionaryVo> findDictionaryList(DictionaryQo dictionaryQo) throws ControllerException {
        List<DictionaryVo> dictionaryVos = new ArrayList<>();
        String dicType = dictionaryQo.getDicType();
        DictionaryVo dictionaryVo;
        String organizationId = "";
        String medicalTechnologyOrganizationId = "";
        QueryInspectionItemListReq queryInspectionItemListReq;
        BaseResponse<List<QueryInspectionItemListResp>> listBaseResponse;

        ParamsOrgQo paramsOrgQo = new ParamsOrgQo();
        if(projectSource.equals(Constants.GOL)){
            paramsOrgQo.setOrganizationId(dictionaryQo.getOrganizationId());
        }else {
            paramsOrgQo.setOrganizationId(dictionaryQo.getOrganizationId());
        }
        BaseResponse response = baseDataService.queryOrganizationList(paramsOrgQo);
        if(null != response && CommonUtils.isNotEmpty(response.getData())){
            List<Map> maps = (List<Map>) response.getData();
            medicalTechnologyOrganizationId = (String) maps.get(0).get("medicalTechnologyOrganizationId");
            organizationId = (String) maps.get(0).get("organizationId");

            if(projectSource.equals(Constants.GOL)){
                String orgId = (String) maps.get(0).get("orgId");
                dictionaryQo.setOrgId(orgId);
            }else {
                dictionaryQo.setOrgId(organizationId);
            }

        }

        //字典类型
        //1:手术字典 本地获取
        //2:手术等级 本地获取
        //3:检查项目 接口获取
        //4:检验项目 接口获取
        //5:药房字典 接口获取
        //6:治疗项目字典
        //7:诊断字典 本地获取
        //8:医生列表 本地获取
        //9:机构列表 本地获取
        //10:处方类型 本地获取
        switch (dicType){
            //手术列表
            case "1":
                dictionaryVos =surgicalTypeDAO.findSurgicalTypeList(dictionaryQo) ;
                break;
            //手术等级
            case "2":
                for (SurgicalLevelEnum surgicalLevelEnum : SurgicalLevelEnum.values()) {
                    dictionaryVo = new DictionaryVo();
                    dictionaryVo.setDicCode(surgicalLevelEnum.getCode());
                    dictionaryVo.setDicName(surgicalLevelEnum.getValue());
                    dictionaryVos.add(dictionaryVo);
                }
                break;
            //检查项目
            case "3":
                QueryCheckItemListReq queryCheckItemListReq = new QueryCheckItemListReq();
                queryCheckItemListReq.setOrganizationId(medicalTechnologyOrganizationId);
                BaseResponse<QueryCheckItemResponse> queryCheckItemResponseBaseResponse = medicalSkillsService.queryCheckItemList(queryCheckItemListReq);
                if(null != queryCheckItemResponseBaseResponse && CommonUtils.isNotEmpty(queryCheckItemResponseBaseResponse.getData())
                        && CommonUtils.isNotEmpty(queryCheckItemResponseBaseResponse.getData().getList())){
                    for (QueryCheckItemListResp queryCheckItemListResp : queryCheckItemResponseBaseResponse.getData().getList()) {
                        dictionaryVo = new DictionaryVo();
                        dictionaryVo.setDicCode(queryCheckItemListResp.getExamMajorItemId());
                        dictionaryVo.setDicName(queryCheckItemListResp.getExamMajorItemName());
                        dictionaryVos.add(dictionaryVo);
                    }
                }
                break;
            //检验项目
            case "4":
                queryInspectionItemListReq = new QueryInspectionItemListReq();
                queryInspectionItemListReq.setOrganizationId(organizationId);
                queryInspectionItemListReq.setPinYinCode(dictionaryQo.getPinyinCode());
                listBaseResponse = examineService.queryInspectionItemList(queryInspectionItemListReq);
                if(null != listBaseResponse && CommonUtils.isNotEmpty(listBaseResponse.getData())){
                    for (QueryInspectionItemListResp queryInspectionItemListResp : listBaseResponse.getData()) {
                        dictionaryVo = new DictionaryVo();
                        dictionaryVo.setDicCode(queryInspectionItemListResp.getInspectionTypeId());
                        dictionaryVo.setDicName(queryInspectionItemListResp.getInspectionTypeName());
                        dictionaryVos.add(dictionaryVo);
                    }
                }
                break;
            //药房列表
            case "5":
                QueryDrugstoreListRequest request = new QueryDrugstoreListRequest();
                QueryDrugstoreListRequest.InnerDepartment department = new QueryDrugstoreListRequest.InnerDepartment();
                request.setDepartment(department);
                department.setVisitOrganization(dictionaryQo.getOrganizationId());
                dictionaryVos = queryDrugstoreListRequest(request);
                break;
            case "6":
                List<TreatmentCodeVo> treatmentCodeVos = treatmentRecordDAO.queryTreatmentCodeList();
                if (CommonUtils.isNotEmpty(treatmentCodeVos)) {
                    for (TreatmentCodeVo treatmentCodeVo : treatmentCodeVos) {
                        dictionaryVo = new DictionaryVo();
                        dictionaryVo.setDicCode(treatmentCodeVo.getTreatmentCode());
                        dictionaryVo.setDicName(treatmentCodeVo.getTreatmentName());
                        dictionaryVos.add(dictionaryVo);
                    }
                }
                break;
            //诊断列表
            case "7":
                //20210929 rpc改造 调cmc
                dictionaryVos = RpcUtil.invoke("cmc.standardDrugService", "getBaseDiseasesList", dictionaryQo.getDiagnosisType(), dictionaryQo.getPinyinCode(), dictionaryQo.getPageNo(), dictionaryQo.getPageSize());
//                dictionaryVos =standardDrugService.getBaseDiseasesList(dictionaryQo.getDiagnosisType(), dictionaryQo.getPinyinCode(), dictionaryQo.getPageNo(), dictionaryQo.getPageSize()) ;
                break;
            case "8":
                //20210929 医生列表 rpc改造 调hcn
                dictionaryVos = baseDataService.getDoctorList(dictionaryQo.getOrganizationId(),dictionaryQo.getDepartmentId(), dictionaryQo.getPinyinCode(),dictionaryQo.getPageNo(), dictionaryQo.getPageSize()) ;
                break;
            case "9":
                //20210929 机构列表 rpc改造 调hcn
                dictionaryVos = baseDataService.getOrgList(dictionaryQo.getPinyinCode(),dictionaryQo.getPageNo(), dictionaryQo.getPageSize()) ;
                break;
                //处方类型
            case "10":
                //20210929 rpc改造 调cmc
                dictionaryVos = RpcUtil.invoke("cmc.electronicMedicalService", "getPrescriptionTypeList",
                        dictionaryQo.getPinyinCode(),dictionaryQo.getOrgId(), dictionaryQo.getPageNo(), dictionaryQo.getPageSize());
//                dictionaryVos =electronicMedicalService.getPrescriptionTypeList(dictionaryQo.getPinyinCode(),dictionaryQo.getOrganizationId(), dictionaryQo.getPageNo(), dictionaryQo.getPageSize()) ;
                break;
            default:
                BaseResponse<List<DictionaryVo>> baseResponse =dictionaryHisService.getHisDictionaryList(dictionaryQo);
                if(CommonUtils.isNotEmpty(baseResponse) && 200 == baseResponse.getCode()){
                    dictionaryVos = baseResponse.getData();
                }
        }
        return dictionaryVos;
    }

    /**
     * @description: 查询机构药房列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/30 13:17
     * @param: request
     * @return: org.atag.core.base.BaseResponse<java.util.List<satisfaction.bean.vo.DictionaryVo>>
     */
    public List<DictionaryVo> queryDrugstoreListRequest(QueryDrugstoreListRequest request) throws ControllerException {
        List<DictionaryVo> dictionaryVos = null;
        DictionaryVo dictionaryVo = null;

        String serviceName = InspectionEmum.QueryDrugstoreList.getCode();
        //组装xml请求入参
        BaseHisPlateformXmlRequest<QueryDrugstoreListRequest> xmlRequest = new BaseHisPlateformXmlRequest<QueryDrugstoreListRequest>();
        //组装MsgHeader
        MsgHeaderRequest msgHeader = new MsgHeaderRequest();
        msgHeader.setMsgType(InspectionEmum.QueryDrugstoreList.getValue());
        msgHeader.setMsgVersion(Constants.MSG_VERSION);
        msgHeader.setOrganization(request.getDepartment().getVisitOrganization());
        msgHeader.setSender(projectSource);
        msgHeader.setServiceType(Constants.SERVICE_TYPE_SERVICE);
        xmlRequest.setMsgHeader(msgHeader);
        //组装MsgBody
        xmlRequest.setMsgBody(request);

        String queryXml = JAXBUtils.object2Xml(new Class[]{BaseHisPlateformXmlRequest.class, QueryDrugstoreListRequest.class}, xmlRequest);
        try {
            //组装soapXml数据
            queryXml = WhisClientUtil.getSoapXmlWithOutBSXml(serviceName, queryXml);
            String xmlStr = WhisClientUtil.getStringDataFromPhis(PHIS_PATH_URL, queryXml);
            BaseHisPlateformXmlResponse xmlResponse = JAXBUtils.xml2Object(xmlStr, BaseHisPlateformXmlResponse.class);
            if(null != xmlResponse){
                //转换数据返回的data字符串
                xmlResponse = JSONObject.parseObject(JSONObject.toJSON(xmlResponse).toString(), BaseHisPlateformXmlResponse.class);
                if(null != xmlResponse){
                    BaseHisPlateformXmlResponse.MsgBody msgBody = xmlResponse.getMsgBody();
                    if (msgBody != null) {
                        String status = msgBody.getStatus();
                        if (status != null && "true".equals(status)) {
                            String data = String.valueOf(xmlResponse.getMsgBody().getData());
                            if (CommonUtils.isNotEmpty(data)) {
                                data = data.replace("UTF-16", "UTF-8");
                                if(CommonUtils.isNotEmpty(data)){
                                    QueryDrugstoreListVo dataVo = JAXBUtils.xml2Object(data, QueryDrugstoreListVo.class);
                                    if(null != dataVo){
                                        List<QueryDrugstoreListVo.DrugstoreInfo> drugstoreInfos = dataVo.getDrugstoreInfos();
                                        if(CommonUtils.isNotEmpty(drugstoreInfos)){
                                            dictionaryVos = new ArrayList<>();
                                            for (QueryDrugstoreListVo.DrugstoreInfo drugstoreInfo : drugstoreInfos) {
                                                dictionaryVo = new DictionaryVo();
                                                dictionaryVo.setDicCode(drugstoreInfo.getPharmacyCode());
                                                dictionaryVo.setDicName(drugstoreInfo.getPharmacyName());
                                                dictionaryVos.add(dictionaryVo);
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            logger.error("查询药房列表失败："+msgBody.getDetail());
                            throw new ControllerException("查询药房列表失败："+msgBody.getDetail());
                        }
                    } else {
                        throw new ControllerException("查询药房列表失败");
                    }
                }
            }
        } catch (Exception e) {
            logger.error("查询药房列表失败="+ e.getMessage());
            throw new ControllerException("查询药房列表失败");

        }
        return dictionaryVos;
    }
}